package icu.lookyousmileface.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.io.FileInputStream;
import java.net.URI;

/**
 * @author shenj
 * @title: ServerHandler
 * @projectName NettyPro
 * @date 2020/12/4 14:39
 * SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
 *客户端和服务端的通信数据被封装为HttpObject对象
 */
public class ServerHandler extends  SimpleChannelInboundHandler<HttpObject>{
    /**
     * @author shenj
     * @title: channelRead0
     * @date 2020/12/4  15:37
     *
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断请求的类型
        if (msg instanceof HttpRequest){
            System.out.println("msg 类型："+msg.getClass());
            System.out.println("客户端地址："+ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest)msg;
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println("客户端请求 /favicon.ico 资源不可达！");
                return;
            }
            //回复信息给浏览器【Http协议】
            ByteBuf dataBuf = Unpooled.copiedBuffer("<h1>世界你好！</h1>"+ctx.channel().remoteAddress().toString().substring(1), CharsetUtil.UTF_8);

            //构造-个http的响应，即HttpResponse
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, dataBuf);
            //设置Header
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, dataBuf.readableBytes());
            //写出并刷新缓冲
            ctx.writeAndFlush(response);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
